package com.dsit.hb950;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.List;

public class WifiAdapter {
	private static final String TAG = WifiAdapter.class.getSimpleName();
	private static WifiAdapter instance = null; // 单例
	static WifiManager.WifiLock wifiLock;
    static Context context;
	// 构造函数
	public static WifiAdapter InitInstance(Context contxt) {
		if (instance == null) {
			synchronized (WifiAdapter.class) {
				instance = new WifiAdapter();
                context = contxt.getApplicationContext();
				String deviceId = instance.getMac();
                //String deviceId = "12345678";
				instance.init(contxt,deviceId);//TODO getIMEI();
				Log.d(TAG, "消息apk WifiAdapter初始化  device IMEI id="+deviceId);
			}
		}
		return instance;
	}

	
	// 析构函数
	public static void FreeInstance() {
		if (instance != null) {
			synchronized (WifiAdapter.class) {
				instance.close();
				instance = null;
			}
		}

	}
	
	private void close(){
		if(wifiMode == Mode_Client){
			CloseWifi();
		}else{
			CloseWifiAp();
		}
	}
	
	private void init(Context contxt,String uuid) {
		// 判断设备ID，否则不启动WIFI热点服务
		//稍后做
		String strDevice = uuid;
		Log.d(TAG, "WIFI初始化时获取的IMEI："+strDevice);
        // 设置热点名
        int nCount = strDevice.length();
        strSSID += strDevice.substring(nCount - 4);
        if (mWifiManager == null) {
            mWifiManager = (WifiManager) contxt.getSystemService(Context.WIFI_SERVICE);
            Log.d(TAG, "Init WifiManger："+mWifiManager.hashCode());
			wifiLock = mWifiManager.createWifiLock("wifilock");
            SetWIFIMode(Mode_AP);// 默认开启热点
        }
	}

	InetAddress getBroadcastAddress() throws IOException {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		DhcpInfo dhcp = wifi.getDhcpInfo();
		// handle null somehow

		int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++)
			quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
		return InetAddress.getByAddress(quads);
	}

	public void wifiLockAquire(){
		wifiLock.acquire();
	}

	public void wifiLockRelease(){
		wifiLock.release();
	}

	public static String getDeviceId(Context contxt){
		String ret = null;
		TelephonyManager tm = (TelephonyManager) contxt.getSystemService(Context.TELEPHONY_SERVICE);
		try {
//            Class<?> c = Class.forName("android.telephony.");
			Method mGetIMEI =tm.getClass().getDeclaredMethod("getImei");

			if (mGetIMEI !=null) {
				ret = (String)mGetIMEI.invoke(tm);
			}
		} catch (Exception e) {
			Log.e(TAG,e.toString());
		}

		if(null == ret || ret.length()<=0){
			ret = tm.getDeviceId();
		}
		Log.e(TAG,"Device ID: "+ret);
		return ret;

//        if (Build.VERSION.SDK_INT == 21)
////            throw new NoSuchMethodError();
//            return tm.getHUDUId();
//        else
//            return tm.getDeviceId();
	}
	public void openWlan(){
		CloseWifiAp();
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}
	}

    // wifi 模式时连接到某一个网络(从扫描得到的网络号)
    public void connectTo(int  netId){
        if(mWifiManager!=null && mWifiManager.isWifiEnabled()){
            mWifiManager.enableNetwork(netId,true);
        }
    }

	private WifiManager mWifiManager = null;

	// 当前WIFI模式(0--WIFI模式，1--热点模式)
	public static final int Mode_Client = 0;
	public static final int Mode_AP     = 1;
	public volatile int wifiMode = 1;	

	public String strSSID = "hb950AP_";	// 热点SSID
	public String strPass = "12345678";// 热点密码
	public String strwSSID = "";		// WIFI_SSID
	public String strwPass = "";		// WIFI_密码

	// WIFI加密方式
	public static final int Pass_no = 1;
	public static final int Pass_wep = 2;
	public static final int Pass_wpa = 3;

	// 设置WIFI模式
	public void SetWIFIMode(int nMode) {
		if (nMode == Mode_Client) {
			if (wifiMode == Mode_AP) {
				// 关闭热点
				CloseWifiAp();
				// 打开WIFI
				CloseWifi();
				if (!OpenWifi()) {
					//如果不能连接，则切回热点模式
					OpenWifiAP();
				}
			}
			Log.d(TAG, "Open Wifi mode finish");
		} else if (nMode == Mode_AP) {
			// 关闭WIFI
			CloseWifi();
			// 设置热点
			OpenWifiAP();
		}
	}

	public class OpenWifiThread extends Thread {
		public void run() {
            if(mWifiManager==null)
                return;
			// 再打开
			if (!mWifiManager.isWifiEnabled()) {
				mWifiManager.setWifiEnabled(true);
			}
			//三次重连
			boolean isConnected = false;
			for (int i = 0; i < 8 ; ++i) {
				//增加
				ConnectivityManager connectivityManager = (ConnectivityManager)
						context.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				if (wifiNetworkInfo.isConnected()) {
					Log.w(TAG,"OpenWifiThread: wifi is connected");
					return;
				}
				//扫描wifi，才能连接
				mWifiManager.startScan();
				try {
					Thread.currentThread();
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			CloseWifi();
			OpenWifiAP();
		}
	}

	private boolean OpenWifi() {
		// 再打开
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}

		// 确保wifi打开
//		int nTime = 0;
//		while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
//			try {
//				Thread.currentThread();
//				Thread.sleep(100);
//				// 超时处理
//				nTime++;
//				if (nTime == 30) {
//					return false;
//				}
//			} catch (InterruptedException e) {
//				Log.e(TAG, "OpenWifi fail = " + e.getMessage());
//			}
//		}
//		Log.d(TAG, "OpenWifi = 1 ");

		//三次重连
		boolean isConnected = false;
		for (int i = 0; i < 6; ++i) {
			//增加
			isConnected = addNetwork();
			if (isConnected) {
				break;
			}
			//扫描wifi，才能连接
			mWifiManager.startScan();
			try {
				Thread.currentThread();
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			List<ScanResult> results = mWifiManager.getScanResults();
			if (null != results)
				Log.d(TAG, results.toString() + results.size());
		}
		return isConnected;
	}


	private boolean addNetwork() {
		boolean flag = false;
		// 删除老的节点
		WifiConfiguration tempConfig = IsExsits(strwSSID);
		if (tempConfig != null) {
			flag = mWifiManager.removeNetwork(tempConfig.networkId);
//			Log.d(TAG,"removeNetwork:netid=" +tempConfig.networkId+";flag=" + flag);
		}
				
		// 建新的连接节点
		WifiConfiguration wifiConfig = CreateWifiInfo(strwSSID, strwPass, Pass_wpa);
		if (wifiConfig == null) {
			return false;
		}

		// 增加新的节点并连接
		int netID = mWifiManager.addNetwork(wifiConfig);
		Log.d(TAG, "addNetwork = 1 : " + netID);
		if (-1 != netID) {			
			flag = mWifiManager.disconnect();
			Log.d(TAG,"disconnect" + flag);
			if( mWifiManager.enableNetwork(netID, false) ){
				flag = mWifiManager.reconnect();
//				Log.d(TAG,"reconnect" + flag);
				wifiMode = Mode_Client;
//				Log.d(TAG, "OpenWifi success");
				return true;
			}			
		}
		return false;
	}
	 
	private void CloseWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	// 查看以前是否也配置过这个网络
	public WifiConfiguration IsExsits(String SSID) {
		List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
		if (existingConfigs != null) {
			for (WifiConfiguration existingConfig : existingConfigs) {
				if (existingConfig.SSID.equals(SSID)) {
					return existingConfig;
				}
			}
		}
		return null;
	}

	// 创建wifi节点
	public WifiConfiguration CreateWifiInfo(String SSID, String Password, int nType) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";
		if (nType == Pass_no) {
			// config.wepKeys[0] = "";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			// config.wepTxKeyIndex = 0;
		} else if (nType == Pass_wep) {
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		} else if (nType == Pass_wpa) {
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
			config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			// config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

			config.status = WifiConfiguration.Status.ENABLED;
		} else {
			return null;
		}
		return config;
	}

//	// AP状态
//	public static final int WIFI_AP_STATE_DISABLING = 10;
//	public static final int WIFI_AP_STATE_DISABLED = 11;
//	public static final int WIFI_AP_STATE_ENABLING = 12;
//	public static final int WIFI_AP_STATE_ENABLED = 13;
//	public static final int WIFI_AP_STATE_FAILED = 14;

	// 设置热点模式
	private void OpenWifiAP() {
		// 关闭热点
		CloseWifiAp();
		// 打开热点
		Method method = null;
		try {
			method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
			WifiConfiguration netConfig = new WifiConfiguration();
			netConfig.SSID = strSSID;
			netConfig.preSharedKey = strPass;
			netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
			netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			if((boolean)method.invoke(mWifiManager, netConfig, true))
				wifiMode = Mode_AP;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		} catch (SecurityException e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "OpenWifiAP fail = " + e.getMessage());
		}

		Log.d(TAG, "OpenWifiAP end");
	}

	// 关闭热点
	public void CloseWifiAp() {
		Log.d(TAG, "CloseWifiAp in");
		if (isWifiApEnabled()) {
			try {
				Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
				method.setAccessible(true);
				WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
				Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
				method2.invoke(mWifiManager, config, false);
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				Log.e(TAG, "CloseWifiAp fail = " + e.getMessage());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
				Log.e(TAG, "CloseWifiAp fail = " + e.getMessage());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				Log.e(TAG, "CloseWifiAp fail = " + e.getMessage());
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				Log.e(TAG, "CloseWifiAp fail = " + e.getMessage());
			}
		}
	}

	// 查询热点是否开启
	private boolean isWifiApEnabled() {
        if(mWifiManager==null)
            return false;
		try {
			Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
			method.setAccessible(true);
			return (Boolean) method.invoke(mWifiManager);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			Log.e(TAG, "isWifiApEnabled fail = " + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "isWifiApEnabled fail = " + e.getMessage());
		}
		return false;
	}

	// 获取热点模式下状态
	public int GetWifiAPState() {
		int nState = 0;
		try {
			Method method = mWifiManager.getClass().getMethod("getWifiApState");
			nState = (Integer) method.invoke(mWifiManager);
			Log.i(TAG, "GetWifiAPState : " + nState);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			Log.e(TAG, "GetWifiAPState fail = " + e.getMessage());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			Log.e(TAG, "GetWifiAPState fail = " + e.getMessage());
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			Log.e(TAG, "GetWifiAPState fail = " + e.getMessage());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			Log.e(TAG, "GetWifiAPState fail = " + e.getMessage());
		}
		return nState;
	}

	// 获取当前IP
	public String GetWifiIP() {
		if (wifiMode == Mode_Client) {
			WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
			return intToIp(wifiinfo.getIpAddress());
		} else if (wifiMode == Mode_AP) {
			return "192.168.43.1";
		}
		return "";
	}

	// 获取广播IP
	public String GetBroadcastIP() {
		if (wifiMode == Mode_Client) {
			return GetBroadcastWifiIP();
		} else if (wifiMode == Mode_AP) {
			return "192.168.43.255";
		}
		return "";
	}

	private String GetBroadcastWifiIP() {
		String strIp = GetWifiIP();
		int nLast = strIp.lastIndexOf(".");
		if (nLast > 0) {
			strIp = strIp.substring(0, nLast) + ".255";
		}
		return strIp;
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
	}

    // 获取wifi Mac地址
	private String getMac()
	{
		String macSerial = null;
		String str = "";
		try
		{
			Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (; null != str;)
			{
				str = input.readLine();
				if (str != null)
				{
                    str = str.replace(":","");
					macSerial = str.trim();// 去空格
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			ex.printStackTrace();
		}
		return macSerial;
	}
}
